package com.dm.cloud.utils.mingexcel.worker;

import com.dm.cloud.utils.mingexcel.annotions.ColumnProperties;
import com.dm.cloud.utils.mingexcel.annotions.DropdownProperties;
import com.dm.cloud.utils.mingexcel.annotions.ExcelProperties;
import com.dm.cloud.utils.mingexcel.entity.TransferItem;
import org.apache.commons.lang3.reflect.MethodUtils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public abstract class SheetReaderFrame {

    //字段转换器
    TransferWorker transferWorker = new TransferWorker();
    //类型
    Class clazz;
    //类型
    int contentStartRow = 0;

    public SheetReaderFrame(Class<?> clazz) throws IllegalAccessException, InstantiationException, InvocationTargetException {
        this.clazz = clazz;
        //先解析类上的注解
        ExcelProperties excelProperties = clazz.getAnnotation(ExcelProperties.class);
        if(null != excelProperties){
            //excel标题
            if(null != excelProperties.title()){
                contentStartRow++;
            }
            //合并行
            if(null != excelProperties.mergedHeaders()){
                contentStartRow = contentStartRow + excelProperties.mergedHeaders().length;
            }
            //表头
            contentStartRow ++;
        }
        //循环字段设置单元格属性
        Field[] tFields = clazz.getDeclaredFields();
        for (int i = 0; i < tFields.length; i++) {
            Field f = tFields[i];
            f.setAccessible(true);
            //列属性 有此属性的字段才导出
            ColumnProperties columnProperties = f.getAnnotation(ColumnProperties.class);
            //下拉框属性
            DropdownProperties dropdownProperties = f.getAnnotation(DropdownProperties.class);
            if(null!=columnProperties){
                if(null !=dropdownProperties){
                    Integer index = columnProperties.index();
                    Class dpclz = dropdownProperties.clazz();
                    //调用方法 返回下拉框列表
                    Object obj = dpclz.newInstance();
                    //获取方法
                    Method method = MethodUtils.getMatchingAccessibleMethod(dpclz, transferWorker.methodName);
                    method.setAccessible(true);
                    //调用方法
                    Object result = method.invoke(obj);

                    if(result!=null && result instanceof TransferItem[]){
                        transferWorker.addFormater(index,(TransferItem[])result);
                    }
                }
            }
        }
    }
}
